<?php

namespace Drupal\shushengyuan\Schemas;

use Drupal\shusy_city\Entity\ShusyCity;

/**
 * @OA\Schema(
 *   schema="CityItem",
 *   type="object",
 *   description="CityItem"
 * )
 */
class CityItem extends AbstractBaseModel {

  protected function getEntityType() {
    return 'shusy_city';
  }

  protected function setValue() {
    if ($this->entity instanceof ShusyCity) {
      [$latitude, $longitude] = $this->context;
      $value = [
        /**
         * @OA\Property(
         *   property="id",
         *   type="integer",
         *   description="ID",
         * ),
         */
        'id' => (int) $this->entity->id,
        /**
         * @OA\Property(
         *   property="name",
         *   type="string",
         *   description="城市名",
         * ),
         */
        'name' => (string) $this->entity->name,
        'weight' => $this->getDistance($latitude, $longitude, $this->entity->latitude, $this->entity->longitude),
      ];
      $this->merge($value);
    }
  }

  protected function getDistance($lat1, $lng1, $lat2, $lng2) {
    //将角度转为狐度
    $radLat1 = deg2rad($lat1);//deg2rad()函数将角度转换为弧度
    $radLat2 = deg2rad($lat2);
    $radLng1 = deg2rad($lng1);
    $radLng2 = deg2rad($lng2);
    $a = $radLat1 - $radLat2;
    $b = $radLng1 - $radLng2;
    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137;
    return $s;
  }
}
